package com.shaoshaohuo.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.GridViewAdapter;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.OrderShopInfoEntity;
import com.shaoshaohuo.app.net.ShopHttpConfig;
import com.shaoshaohuo.app.utils.BitmapUtils;
import com.shaoshaohuo.app.utils.Okhttputils;
import com.shaoshaohuo.app.view.ApplyBackDialog;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.Call;
import okhttp3.Response;

public class ApplyBackMoney extends AppCompatActivity implements View.OnClickListener, View.OnTouchListener, TextWatcher, ApplyBackDialog.dialogListener {

    /**
     * tobar
     */
    private ImageView order_tobar_back;
    private TextView order_tobar_enter;
    private ImageView order_tobar_right;
    private LinearLayout order_layout_topbar_left;
    /**
     * 申请退款
     */
    private RelativeLayout apply_back_money_reason;
    private OrderShopInfoEntity.DataBean dataBean;
    /**
     * 退款的商品信息
     */
    private TextView apply_back_money_shop_name;
    private TextView apply_back_money_shop_mbn_details;
    private TextView apply_back_money_shop_details;
    private TextView apply_back_money_shop_money;
    private ImageView apply_back_money_shop_picture;
    private TextView apply_back_money_shop_peiSong;
    private TextView apply_back_money_lengLian;
    private EditText apply_back_moey_all_money;
    private EditText apply_back_moey_input_explain;
    private Button apply_back_money_commit;
    private ImageView apply_back_moey_pingzheng;
    private List<File> fileList;
    private List<String> grid_data;
    private GridView apply_back_moey_gridView;
    private GridViewAdapter adapter;
    private HorizontalScrollView release_shop_horscrolistView;
    private TextView apply_back_money_xiansi;
    private ApplyBackDialog applyBackDialog;
    private ApplyBackListener applyBackListener;
    private TextView apply_more_money;
    public ApplyBackMoney newInstance(Intent intent, OrderShopInfoEntity.DataBean dataBean) {
        ApplyBackMoney applyBackMoney = new ApplyBackMoney();
        Bundle bundle = new Bundle();
        bundle.putSerializable("intentdata", dataBean);
        intent.putExtras(bundle);
        return applyBackMoney;
    }

    public void getIntentData() {
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            dataBean = (OrderShopInfoEntity.DataBean) extras.getSerializable("intentdata");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_back_money);
        getIntentData();
        initView();
        setView();
        initListener();
    }

    private void setView() {
        apply_back_money_shop_name.setText(dataBean.getName());
        apply_back_money_shop_mbn_details.setText(dataBean.getMbn_details());
        String fin_money = dataBean.getFin_money();
        String buy_num = dataBean.getBuy_num();
        apply_back_money_shop_details.setText("￥" + Float.valueOf(fin_money) / Float.valueOf(buy_num) + "/件");
        apply_back_money_shop_money.setText("×" + dataBean.getBuy_num());
        Picasso.with(this).load(dataBean.getImg()).into(apply_back_money_shop_picture);
//        if (dataBean.getFin_money() != null && dataBean.getBuy_num() != null) {
//            apply_back_moey_all_money.setText("￥" + Double.valueOf(dataBean.getBuy_num()) * Double.valueOf(dataBean.getFin_money()));
//        }
    }

    private void initListener() {
        apply_back_money_reason.setOnClickListener(this);
        apply_back_moey_input_explain.setOnTouchListener(this);
        apply_back_moey_input_explain.addTextChangedListener(this);
        apply_back_moey_pingzheng.setOnClickListener(this);
        apply_back_money_commit.setOnClickListener(this);
        order_tobar_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        applyBackDialog.setListener(this);

    }

    private void initView() {
        /**
         * tobar
         * */
        order_layout_topbar_left = (LinearLayout) findViewById(R.id.layout_topbar_left);
        order_layout_topbar_left.setVisibility(View.VISIBLE);
        order_tobar_back = (ImageView) findViewById(R.id.imageview_topbar_left_backImage);
        order_tobar_back.setVisibility(View.VISIBLE);
        order_tobar_back.setImageResource(R.mipmap.return_key);
        order_tobar_enter = (TextView) findViewById(R.id.toolbar_topname);
        order_tobar_enter.setText("申请退款");
        order_tobar_right = (ImageView) findViewById(R.id.imageview_message);
        order_tobar_right.setVisibility(View.GONE);

        //申请退款
        apply_back_money_reason = (RelativeLayout) findViewById(R.id.apply_back_money_reason);
        apply_back_money_shop_name = (TextView) findViewById(R.id.apply_back_money_shop_name);
        apply_back_money_shop_mbn_details = (TextView) findViewById(R.id.apply_back_money_shop_mbn_details);
        apply_back_money_shop_details = (TextView) findViewById(R.id.apply_back_money_shop_details);
        apply_back_money_shop_money = (TextView) findViewById(R.id.apply_back_money_shop_money);
        apply_back_money_shop_picture = (ImageView) findViewById(R.id.apply_back_money_shop_picture);
        apply_back_moey_all_money = (EditText) findViewById(R.id.apply_back_moey_all_money);
        apply_back_moey_input_explain = (EditText) findViewById(R.id.apply_back_moey_input_explain);
        apply_more_money = (TextView) findViewById(R.id.apply_more_money);
        apply_more_money.setText("最多￥" + dataBean.getFin_money() + "  含发货邮费￥0.00");
        apply_back_moey_pingzheng = (ImageView) findViewById(R.id.apply_back_moey_pingzheng);
        apply_back_moey_gridView = (GridView) findViewById(R.id.apply_back_moey_gridView);
        fileList = new ArrayList<>();
        grid_data = new ArrayList<>();

        apply_back_money_xiansi = (TextView) findViewById(R.id.apply_back_money_xiansi);
        apply_back_money_commit = (Button) findViewById(R.id.apply_back_money_commit);

        applyBackDialog = new ApplyBackDialog(this);
        release_shop_horscrolistView = (HorizontalScrollView) findViewById(R.id.release_shop_horscrolistView);
    }

    public static void tackPic(ArrayList<String> mSelectPath, Intent intent2, int selectedMode, int maxNum) {
//        int selectedMode = MultiImageSelectorActivity.MODE_MULTI;
//        int maxNum = 10;
//        Intent intent2 = new Intent(mContext, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent2.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大可选择图片数量
        intent2.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
        // 选择模式
        intent2.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);
        // 默认选择
        if (mSelectPath != null && mSelectPath.size() > 0) {
            intent2.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
        }

    }

    private ArrayList<String> pathlist = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 6) {
            if (data != null) {
                ArrayList<String> select_result = data.getStringArrayListExtra("select_result");
                if (select_result != null && select_result.size() > 0) {
                    for (int i = 0; i < select_result.size(); i++) {
                        String item_picture = select_result.get(0);
                        File zipbit = BitmapUtils.zipbit(item_picture, getApplicationContext());
//                        File fil_picture = new File(item_picture);
                        fileList.add(zipbit);
                        grid_data.add(zipbit.getAbsolutePath());
                    }
                    if (fileList != null && fileList.size() > 0) {
                        apply_back_moey_gridView.setVisibility(View.VISIBLE);
                        release_shop_horscrolistView.setVisibility(View.VISIBLE);
                        if (fileList.size() >= 6) {
                            apply_back_moey_pingzheng.setVisibility(View.GONE);
                        }
                        adapter = new GridViewAdapter(getApplicationContext(), grid_data);
                        horizontal_layout();
                        apply_back_moey_gridView.setAdapter(adapter);
                        adapter.setDelete(new GridViewAdapter.Delete() {
                            @Override
                            public void delete() {
                                if (adapter.getCount() < 6) {
                                    apply_back_moey_pingzheng.setVisibility(View.VISIBLE);
                                }
                            }
                        });
                    }
                }
            }
        }
    }

    public void horizontal_layout() {
        int size = fileList.size();
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int allWidth = (int) (110 * size * density);
        int itemWidth = (int) (100 * density);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                allWidth, LinearLayout.LayoutParams.FILL_PARENT);
        apply_back_moey_gridView.setLayoutParams(params);// 设置GirdView布局参数
        apply_back_moey_gridView.setColumnWidth(itemWidth);// 列表项宽
        apply_back_moey_gridView.setHorizontalSpacing(15);// 列表项水平间距
        apply_back_moey_gridView.setStretchMode(GridView.NO_STRETCH);
        apply_back_moey_gridView.setNumColumns(size);//总长度
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.apply_back_money_reason:
                applyBackDialog.show();
                break;
            case R.id.apply_back_moey_pingzheng:
                Intent intent = new Intent();
                tackPic(pathlist, intent, 1, 6);
                intent.setClass(getApplicationContext(), MultiImageSelectorActivity.class);
                startActivityForResult(intent, 6);
                break;
            case R.id.apply_back_money_commit:
                requestData();
                break;
        }

    }

    public void setApplyBackListener(ApplyBackListener applyBackListener) {
        this.applyBackListener = applyBackListener;
    }

    public interface ApplyBackListener {
        void BackMonyIfsuccess(int code);
    }

    private void requestData() {
        if (apply_back_moey_all_money.getText().toString().trim() != null && apply_back_money_xiansi.getText().toString().trim() != null) {
            String money = apply_back_moey_all_money.getText().toString().trim();
            String details_reson = apply_back_money_xiansi.getText().toString().trim();
            String reason = apply_back_moey_input_explain.getText().toString().trim();
            String orderid = dataBean.getOrderid();
            String type = "1";
            Log.e("退款参数", fileList.size() + "====" + orderid + "==" + details_reson + "==" + reason);
            ShopHttpConfig.applyBackMoney(getApplicationContext(), fileList, type, orderid, money, details_reson, reason, new Okhttputils.OkutListener() {
                @Override
                public void error(Call call, IOException e) {

                }

                @Override
                public void error(Call call, int code) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "申请失败", Toast.LENGTH_SHORT).show();
                        }
                    });

                }

                @Override
                public void suseff(Call call, Response response, Object o) {
                    Log.e("申请退款", "退款成功");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "申请成功", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    });
                }
            }, BaseEntity.class);
        } else if (apply_back_moey_all_money.getText().toString().trim() == null) {
            Toast.makeText(getApplicationContext(), "请输入退款金额", Toast.LENGTH_SHORT).show();
        } else if (apply_back_money_xiansi.getText().toString().trim() == null) {
            Toast.makeText(getApplicationContext(), "请选择退款原因", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        apply_back_moey_input_explain.setHint("");
        apply_back_moey_input_explain.setCursorVisible(true);
        return false;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        Log.e("输入退款原因", s.toString());
        Toast.makeText(this, s.toString(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void afterTextChanged(Editable s) {
    }


    @Override
    public void listItemListener(int position, List<String> data) {
        apply_back_money_xiansi.setVisibility(View.VISIBLE);
        apply_back_money_xiansi.setText(data.get(position));
    }
}
